<template>
    <el-dialog
        v-model="state.visible"
        title="设置解锁密码"
        width="25%"
        align-center
        destroy-on-close
        modal-class="black-modal"
        :close-on-click-modal="false"
    >
        <el-form ref="pwdFormRef" :model="pwd" :rules="pwdRules">
            <el-form-item prop="0">
                <el-input
                    type="password"
                    v-model="pwd[0]"
                    size="large"
                    placeholder="设置密码"
                >
                </el-input>
            </el-form-item>
            <el-form-item prop="1">
                <el-input
                    type="password"
                    v-model="pwd[1]"
                    size="large"
                    placeholder="确认密码"
                >
                </el-input>
            </el-form-item>
            <el-form-item>
                <div class="flex flex-1 justify-end">
                    <el-button type="primary" size="large" @click="handleSetPwd"
                        >确认</el-button
                    >
                </div>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue'

const state = reactive({
    visible: false
})

const pwdRules = [
    {
        validator: (rule, value, cb) => {
            if (!value) {
                cb('请设置新的解锁密码')
            } else if (value.length < 6) {
                cb('解锁密码长度小于6位')
            } else {
                cb()
            }
        },
        trigger: 'blur'
    },
    {
        validator: (rule, value, cb) => {
            if (!value) {
                cb('请重新输入新的解锁密码')
            } else if (value !== pwd.value[0]) {
                cb('两次密码不一致')
            } else {
                cb()
            }
        },
        trigger: 'blur'
    }
]

/**
 * 密码
 */
const pwd = ref([])
/**
 * 密码
 */
const pwdFormRef = ref()

// 开启弹窗
const open = (boxNum) => {
    state.visible = true
}

// 关闭弹窗
const close = () => {
    state.visible = false
}

/**
 * 确认密码并且保存密码
 */
async function handleSetPwd() {
    try {
        await pwdFormRef.value.validate()
        localStorage.setItem('pwd', pwd.value[0])
        state.visible = false
    } catch (error) {
        console.log(error)
    }
}

defineExpose({ open, close })
</script>